<template>
  <div class="login_form">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="form">
      <h1 class="title">易果生鲜会员管理系统</h1>
      <el-form-item label="账号:" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input v-model="ruleForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="验证码:" prop="text">
        <el-input v-model="ruleForm.code"></el-input>
        <template>
          <img :src="imgurl" @click="changeimg" class="loginimg" />
        </template>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登陆</el-button>
      </el-form-item>
    </el-form>
    <ul>
      <li>666</li>
    </ul>
  </div>
</template>

<script>
import loginApi from "@/api/login";

export default {
  data() {
    return {
      imgurl: "http://www.defihome.xyz/api/user/code/?",
      ruleForm: {
        name: "",
        password: "",
        code: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入账号", trigger: "blur" }]
      }
    };
  },

  components: {},

  methods: {
    //切换验证码
    changeimg() {
      this.imgurl = "http://www.defihome.xyz/api/user/code/?" + new Date();
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        // console.log(valid);
        if (valid) {
          //正则验证通过
          //发送请求：把账号和密码提交到后端

          //调用actions的方法，进行登陆
          try {
            //第一个请求：
            let p = await this.$store.dispatch("Login", this.ruleForm);

            if (p.flag) {
              //第二个请求：第一个请求成功了，才能发送第二个请求
              //发送请求，获取用户信息
              let res = await this.$store.dispatch("GetUserInfo");

              if (res.flag) {
                //成功跳转到首页
                this.$router.push("/home");
              }
            }
          } catch (err) {
            console.log(err);
          }

          // console.log(p);
        } else {
          //失败：输入信息不对
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
@import "~@/assets/css/login.css";
.loginimg {
  background-color: aliceblue;
}
</style>